﻿using System;
using System.Collections.Generic;
using System.IO;
using Docentric.Word;


namespace Docentric.Examples.Browser
{
	public class MergingSubDocumentsExample : ExampleBase
	{
		// Constructor
		public MergingSubDocumentsExample()
		{
			Name = "MergingSubDocuments";
			Title = "Merging (Sub)Documents";
			Description = "It is also possible to merge Sub-Documents into another document. This example shows how you can use 'SubDocument' element to insert a sub-document on a document.";
		}


		// GenerateReport
		public override string GenerateReport()
		{
			// Read SubDocument1 and SubDocument2 documents.
			byte[] subDocument1Data = File.ReadAllBytes(System.IO.Path.Combine(ApplicationPath, "ExampleResources\\" + Name + "\\SubDocument1.docx"));
			byte[] subDocument2Data = File.ReadAllBytes(System.IO.Path.Combine(ApplicationPath, "ExampleResources\\" + Name + "\\SubDocument2.docx"));

			// Create a temporary file for the generated report document.
			string reportDocumentFileName = System.IO.Path.GetTempPath() + "GeneratedReport_" + Guid.NewGuid().ToString() + ".docx";
			using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
			{
				// Open the report template file.
				using (Stream reportTemplateStream = GetReportTemplate())
				{
					// Generate the report document using 'DocumentGenerator'.
					DocumentGenerator dg = new DocumentGenerator(subDocument1Data);
					dg.SetNamedDataSourceValue("SubDocument2", subDocument2Data);
					DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);
					if (result.HasErrors)
					{
						foreach (Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);
					}
				}
			}

			return reportDocumentFileName;
		}
	}
}
